<template>
    <div class="scholarship-container">
      <div class="header">
        <div class="left">
          <h2>奖学金项目</h2>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>添加项目
          </el-button>
        </div>
        <div class="right">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索项目"
            clearable
            @clear="handleSearch"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
      </div>
  
      <el-card class="table-card">
        <el-table
          v-loading="loading"
          :data="scholarships"
          border
          stripe
          style="width: 100%"
        >
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="title" label="项目名称" min-width="150" />
          <el-table-column prop="amount" label="金额" width="120">
            <template #default="{ row }">
              ¥{{ row.amount }}
            </template>
          </el-table-column>
          <el-table-column prop="quota" label="名额" width="100" />
          <el-table-column label="申请时间" width="300">
            <template #default="{ row }">
              {{ formatDate(row.startTime) }} 至 {{ formatDate(row.endTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button
                type="primary"
                size="small"
                @click="handleEdit(row)"
              >
                编辑
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="handleDelete(row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
  
        <div v-if="!loading && (!scholarships || scholarships.length === 0)" class="empty-data">
          <el-empty description="暂无数据" />
        </div>
  
        <div class="pagination">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="total"
            :page-sizes="[10, 20, 50]"
            layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
  
      <!-- 添加/编辑对话框 -->
      <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="600px"
      >
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="项目名称" prop="title">
            <el-input v-model="form.title" placeholder="请输入项目名称" />
          </el-form-item>
          <el-form-item label="金额" prop="amount">
            <el-input-number
              v-model="form.amount"
              :min="0"
              :precision="2"
              :step="100"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="名额" prop="quota">
            <el-input-number
              v-model="form.quota"
              :min="1"
              :precision="0"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="申请时间" prop="timeRange">
            <el-date-picker
              v-model="form.timeRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input
              v-model="form.description"
              type="textarea"
              :rows="3"
              placeholder="请输入项目描述"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            :loading="submitting"
            @click="handleSubmit"
          >
            确定
          </el-button>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted } from 'vue'
  import { Plus, Search } from '@element-plus/icons-vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { getScholarships, createScholarship, updateScholarship, deleteScholarship } from '@/api/admin/scholarship'
  import { formatDate } from '@/utils/format'
  
  // 表格数据
  const loading = ref(false)
  const scholarships = ref([])
  const total = ref(0)
  const currentPage = ref(1)
  const pageSize = ref(10)
  const searchKeyword = ref('')
  
  // 获取奖学金列表
  const fetchScholarships = async () => {
    try {
      loading.value = true
      const response = await getScholarships({
        page: currentPage.value - 1,
        size: pageSize.value,
        keyword: searchKeyword.value
      })
      
      if (response) {
        scholarships.value = response.content
        total.value = response.totalElements
      }
    } catch (error) {
      console.error('Failed to fetch scholarships:', error)
      ElMessage.error('获取奖学金项目失败')
    } finally {
      loading.value = false
    }
  }
  
  // 处理搜索
  const handleSearch = () => {
    currentPage.value = 1
    fetchScholarships()
  }
  
  // 处理分页
  const handleSizeChange = (val) => {
    pageSize.value = val
    fetchScholarships()
  }
  
  const handleCurrentChange = (val) => {
    currentPage.value = val
    fetchScholarships()
  }
  
  // 表单相关
  const dialogVisible = ref(false)
  const dialogTitle = ref('添加奖学金项目')
  const formRef = ref(null)
  const submitting = ref(false)
  
  const form = ref({
    title: '',
    amount: 0,
    quota: 1,
    timeRange: [],
    description: ''
  })
  
  const rules = {
    title: [
      { required: true, message: '请输入项目名称', trigger: 'blur' }
    ],
    amount: [
      { required: true, message: '请输入金额', trigger: 'change' }
    ],
    quota: [
      { required: true, message: '请输入名额', trigger: 'change' }
    ],
    timeRange: [
      { required: true, message: '请选择申请时间', trigger: 'change' }
    ],
    description: [
      { required: true, message: '请输入项目描述', trigger: 'blur' }
    ]
  }
  
  const handleAdd = () => {
    dialogTitle.value = '添加奖学金项目'
    form.value = {
      title: '',
      amount: 0,
      quota: 1,
      timeRange: [],
      description: ''
    }
    dialogVisible.value = true
  }
  
  const handleEdit = (row) => {
    dialogTitle.value = '编辑奖学金项目'
    form.value = {
      id: row.id,
      title: row.title,
      amount: row.amount,
      quota: row.quota,
      timeRange: [row.startTime, row.endTime],
      description: row.description
    }
    dialogVisible.value = true
  }
  
  const handleDelete = (row) => {
    ElMessageBox.confirm('确定要删除该奖学金项目吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      try {
        await deleteScholarship(row.id)
        ElMessage.success('删除成功')
        fetchScholarships()
      } catch (error) {
        console.error('Delete failed:', error)
        ElMessage.error('删除失败')
      }
    })
  }
  
  const handleSubmit = async () => {
    if (!formRef.value) return
    
    try {
      await formRef.value.validate()
      submitting.value = true
      
      const [startTime, endTime] = form.value.timeRange
      const data = {
        ...form.value,
        startTime: startTime.replace(' ', 'T'),
        endTime: endTime.replace(' ', 'T')
      }
      delete data.timeRange

      console.log('Submit data:', data)
      
      if (form.value.id) {
        await updateScholarship(form.value.id, data)
        ElMessage.success('更新成功')
      } else {
        await createScholarship(data)
        ElMessage.success('添加成功')
      }
      
      dialogVisible.value = false
      fetchScholarships()
    } catch (error) {
      console.error('Form submission failed:', error)
      ElMessage.error(error.response?.data || '提交失败')
    } finally {
      submitting.value = false
    }
  }
  
  // 在组件挂载时获取数据
  onMounted(() => {
    fetchScholarships()
  })
  </script>
  
  <style scoped>
  .scholarship-container {
    padding: 20px;
  }
  
  .header {
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .left {
    display: flex;
    align-items: center;
    gap: 16px;
  }
  
  .right {
    display: flex;
    gap: 16px;
  }
  
  .table-card {
    margin-bottom: 20px;
  }
  
  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  .empty-data {
    padding: 40px 0;
    text-align: center;
  }
  </style> 